// 意见反馈页面
const auth = require('../../utils/auth.js');
const { mapMediaUrls, buildMediaUrl } = require('../../utils/media.js');
const app = getApp();

Page({
  data: {
    userInfo: {},
    
    // 反馈表单
    feedback: {
      type: 'bug', // bug, suggestion, other
      title: '',
      content: '',
      contact: '',
      images: []
    },
    
    // 反馈类型
    feedbackTypes: [
      { value: 'bug', label: '功能故障', icon: '🐛', description: '应用功能异常或错误' },
      { value: 'suggestion', label: '功能建议', icon: '💡', description: '新功能建议或改进意见' },
      { value: 'other', label: '其他问题', icon: '❓', description: '其他类型的反馈' }
    ],
    
    submitting: false,
    
    // 历史反馈
    feedbackHistory: []
  },

  onLoad: function() {
    this.loadUserInfo();
    this.loadFeedbackHistory();
  },

  // 加载用户信息
  loadUserInfo: function() {
  const userInfo = auth.getCurrentUser && auth.getCurrentUser();
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        'feedback.contact': userInfo.phone || userInfo.email || ''
      });
    }
  },

  // 加载反馈历史
  loadFeedbackHistory: function() {
    if (!auth.getToken()) return;

    wx.request({
  url: `${app.globalData.apiBaseUrl}/feedback/history`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`
      },      success: (res) => {
        if (res.statusCode === 200 && (res.data.success || res.data.code === 0)) {
          const historyData = res.data.data || [];
          // 使用标准工具处理历史记录中的图片URL
          const processedHistory = historyData.map(item => ({
            ...item,
            images: mapMediaUrls(item.images || [])
          }));
          this.setData({
            feedbackHistory: processedHistory
          });
        }
      },
      fail: (error) => {
        console.error('加载反馈历史失败:', error);
      }
    });
  },

  // 选择反馈类型
  selectFeedbackType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      'feedback.type': type
    });
  },

  // 输入标题
  onTitleInput: function(e) {
    this.setData({
      'feedback.title': e.detail.value
    });
  },

  // 输入内容
  onContentInput: function(e) {
    this.setData({
      'feedback.content': e.detail.value
    });
  },

  // 输入联系方式
  onContactInput: function(e) {
    this.setData({
      'feedback.contact': e.detail.value
    });
  },

  // 选择图片
  chooseImages: function() {
    const currentImages = this.data.feedback.images;
    const remainingCount = 3 - currentImages.length;

    if (remainingCount <= 0) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      });
      return;
    }

    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const newImages = [...currentImages, ...res.tempFilePaths];
        this.setData({
          'feedback.images': newImages
        });
      },
      fail: (error) => {
        console.error('选择图片失败:', error);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  // 预览图片
  previewImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.feedback.images;
    
    // 处理图片URL，支持本地临时路径和服务器相对路径
    const imageUrls = images.map(img => {
      // 如果是本地临时路径，直接返回
      if (img.startsWith('tmp/') || img.includes('tmp') || img.startsWith('wxfile://')) {
        return img;
      }
      // 如果是服务器相对路径，使用标准工具转换
      return buildMediaUrl(img);
    });
    
    wx.previewImage({
      current: imageUrls[index],
      urls: imageUrls
    });
  },

  // 删除图片
  deleteImage: function(e) {
    e.stopPropagation();
    const index = e.currentTarget.dataset.index;
    const images = this.data.feedback.images;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          images.splice(index, 1);
          this.setData({
            'feedback.images': images
          });
        }
      }
    });
  },

  // 提交反馈
  submitFeedback: function() {
    const { feedback } = this.data;

    // 验证表单
    if (!feedback.title.trim()) {
      wx.showToast({
        title: '请输入反馈标题',
        icon: 'none'
      });
      return;
    }

    if (!feedback.content.trim()) {
      wx.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      });
      return;
    }

    if (feedback.content.trim().length < 10) {
      wx.showToast({
        title: '反馈内容至少10个字符',
        icon: 'none'
      });
      return;
    }

    this.setData({ submitting: true });

    // 如果有图片，先上传图片
    if (feedback.images.length > 0) {
      this.uploadImagesAndSubmit();
    } else {
      this.submitFeedbackData();
    }
  },

  // 上传图片并提交
  uploadImagesAndSubmit: function() {
    const images = this.data.feedback.images;
    const uploadPromises = images.map(imagePath => new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${app.globalData.apiBaseUrl}/upload/image?category=feedback`,
        filePath: imagePath,
        name: 'image',
        formData: { category: 'feedback' },
        header: { 'Authorization': `Bearer ${auth.getToken()}` },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.success) resolve(data.data.url);
            else reject(new Error(data.message || '上传失败'));
          } catch (e) { reject(new Error('上传响应解析失败')); }
        },
        fail: (err) => reject(new Error(err.errMsg || '上传失败'))
      });
    }));

    Promise.all(uploadPromises)
      .then(imageUrls => {
        this.setData({
          'feedback.images': imageUrls
        });
        this.submitFeedbackData();
      })
      .catch(error => {
        console.error('上传图片失败:', error);
        this.setData({ submitting: false });
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        });
      });
  },

  // 提交反馈数据
  submitFeedbackData: function() {
    wx.request({
  url: `${app.globalData.apiBaseUrl}/feedback`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`,
        'Content-Type': 'application/json'
      },
      data: this.data.feedback,
      success: (res) => {
        this.setData({ submitting: false });
        
  if (res.statusCode === 200 && (res.data.success || res.data.code === 0)) {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          
          // 重置表单
          this.resetForm();
          
          // 刷新历史记录
          this.loadFeedbackHistory();
        } else {
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        this.setData({ submitting: false });
        console.error('提交反馈失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 重置表单
  resetForm: function() {
    this.setData({
      feedback: {
        type: 'bug',
        title: '',
        content: '',
        contact: this.data.userInfo.phone || this.data.userInfo.email || '',
        images: []
      }
    });
  },

  // 查看反馈详情
  viewFeedbackDetail: function(e) {
    const feedback = e.currentTarget.dataset.feedback;
    
    // 跳转到详情页面
    wx.navigateTo({
      url: `/pages/feedback/detail/detail?id=${feedback.id}`
    });
  },

  // 获取反馈类型文本
  getFeedbackTypeText: function(type) {
    const typeObj = this.data.feedbackTypes.find(t => t.value === type);
    return typeObj ? typeObj.label : '其他';
  },

  // 获取反馈状态文本
  getFeedbackStatusText: function(status) {
    const statusMap = {
      'pending': '待处理',
      'processing': '处理中',
      'resolved': '已解决',
      'closed': '已关闭'
    };
    return statusMap[status] || '未知状态';
  },

  // 获取反馈状态样式
  getFeedbackStatusClass: function(status) {
    const classMap = {
      'pending': 'pending',
      'processing': 'processing',
      'resolved': 'resolved',
      'closed': 'closed'
    };
    return classMap[status] || 'pending';
  },

  // 格式化日期
  formatDate: function(dateString) {
    const date = new Date(dateString);
    return `${date.getMonth() + 1}-${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  }
});
